package com.gf.exam.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gf.base.dao.impl.BaseDaoImpl;
import com.gf.exam.dao.AnswerCellDao;
import com.gf.exam.mapper.AnswerCellMapper;
import com.gf.exam.model.AnswerCell;

@Service("answerCellDao")
public class AnswerCellDaoImpl extends BaseDaoImpl implements AnswerCellDao {

	/**
	 * insert into answercell
	 * (answerId,cellId,answerRight,mouseAction,inputAction,rt) values
	 * (?,?,?,?,?,?)
	 */
	@Value("${answerCellDao.insertBatchSql}")
	private String insertBatchSql;

	/**
	 * select * from answercell where answerId=? order by cellId asc
	 */
	@Value("${answerCellDao.queryAnswerCellsSql}")
	private String queryAnswerCellsSql;

	/**
	 * select * from answercell where answerId in (?) order by answerId
	 * asc,cellId asc
	 */
	@Value("${answerCellDao.queryAnswerCellsSql2}")
	private String queryAnswerCellsSql2;

	@Override
	public int insertBatch(int cellNo, long answerId, String[] answerRight,
			String[] mouseAction, String[] inputAction, String[] rt) {

		List<Object[]> argsList = new ArrayList<Object[]>();

		for (int i = 0; i < cellNo; i++) {
			Object[] obj = new Object[6];
			obj[0] = answerId;
			obj[1] = i;// 第几题
			obj[2] = answerRight[i];
			obj[3] = mouseAction[i];
			obj[4] = inputAction[i];
			obj[5] = rt[i];

			argsList.add(obj);
		}

		return this.batchInsertWithIdReturn(insertBatchSql, argsList).size();
	}

	@Override
	public List<AnswerCell> queryAnswerCells(long answerId) {

		return jdbcTemplate.query(queryAnswerCellsSql,
				new Object[] { answerId }, AnswerCellMapper.getMapper());
	}

	@Override
	public Map<Long, List<AnswerCell>> queryAnswerCells(List<Long> answerIds) {
		if (answerIds == null || answerIds.size() == 0) {
			return new HashMap<Long, List<AnswerCell>>();
		}

		String answerIdStr = "" + answerIds.get(0);
		for (int i=1;i<answerIds.size();++i) {
			answerIdStr += ("," + answerIds.get(i));
		}
		/**
		 * 注入的形式不可用
		 */
		List<AnswerCell> lists = jdbcTemplate.query("select * from answercell where answerId in ("+answerIdStr+") order by answerId asc,cellId asc",
				AnswerCellMapper.getMapper());

		
		if (lists == null || lists.size() == 0) {
			return new HashMap<Long, List<AnswerCell>>();
		}

		Map<Long, List<AnswerCell>> result = new HashMap<Long, List<AnswerCell>>();
		for (AnswerCell ac : lists) {
			Long ansewerId = ac.getAnswerId();
			if (result.containsKey(ansewerId)) {
				result.get(ansewerId).add(ac);
			} else {
				List<AnswerCell> temp = new ArrayList<AnswerCell>();
				temp.add(ac);
				result.put(ansewerId, temp);
			}
		}
		
		return result;
	}

}
